package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author ck
 * @date 2021/10/13 11:46
 */
@Service
@Slf4j
@Transactional
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品基础信息，向dish表插入数据
        this.save(dishDto);
        //菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        //批量保存菜品口味数据，向dish_flavor表插入数据

        dishFlavorService.saveBatch(flavors);

        //清理所有菜品的缓存数据
        // Set keys = redisTemplate.keys("dish_*");


        //精确清理，只是清理某个分类下面的菜品缓存
        String key = "dish_" + dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
    }

    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //修改菜品信息
        this.updateById(dishDto);

        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        //删除当前菜品关联的口味信息
        dishFlavorService.remove(queryWrapper);

        List<DishFlavor> list = dishDto.getFlavors();

        list = list.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        //重新保存当前菜品关联的口味信息
        dishFlavorService.saveBatch(list);


        //清理所有菜品的缓存数据
        // Set keys = redisTemplate.keys("dish_*");


        //精确清理，只是清理某个分类下面的菜品缓存
        String key = "dish_" + dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);

    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     *
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //根据id查询菜品
        Dish dish = this.getById(id);

        DishDto dishDto = new DishDto();

        BeanUtils.copyProperties(dish, dishDto);
        //条件构造器
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        //设置菜品对应的口味信息
        dishDto.setFlavors(list);
        return dishDto;
    }

    @Override
    public void updateWithStatus(int status, List<Long> ids) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId, ids);

        List<Dish> list = this.list(queryWrapper);

        list = list.stream().map(item -> {
            item.setStatus(status);
            this.updateById(item);
            return item;
        }).collect(Collectors.toList());

    }

    @Override
    public void deleteByIds(List<Long> ids) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId, ids);
        this.remove(queryWrapper);

        LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(DishFlavor::getDishId, ids);

        dishFlavorService.remove(queryWrapper1);
    }

    @Override
    public R<Page> pageCat(int page, int pageSize, String name) {
        //构造分页构造器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //执行分页
        dishService.page(pageInfo, queryWrapper);

        Page<DishDto> resPage = new Page<>(page, pageSize);
        BeanUtils.copyProperties(pageInfo, resPage, "records");

        resPage.setRecords(pageInfo.getRecords().stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Category ca = categoryService.getById(item.getCategoryId());
            if (ca != null) {
                dishDto.setCategoryName(ca.getName());
            }
            return dishDto;
        }).collect(Collectors.toList()));
        //结果返回

        return R.success(resPage);
    }

    @Override
    public R<List<DishDto>> catList(Dish dish) {

        List<DishDto> listd = null;

        //动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();


        //先从redis中获取缓存数据
        listd = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if (listd != null) {
            //如果存在，直接返回，无需查询数据库
            return R.success(listd);
        }


        //构建条件查询
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus, 1);
        queryWrapper.orderByDesc(Dish::getSort).orderByAsc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);
        //遍历集合
        listd = list.stream().map(item -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();

            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            Long id = item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId, id);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper1);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到redis
        //只存在60分钟 六十分钟之后自动销毁
        redisTemplate.opsForValue().set(key,listd,60, TimeUnit.MINUTES);


        return R.success(listd);
    }
}
